package com.example.orderservice.infra.thread;

import com.google.common.collect.Maps;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfigurations {

    private static final ConcurrentMap<String, ExecutorService> EXECUTOR_SERVICE_LOADING_CACHE = Maps.newConcurrentMap();

    // 任务队列
    public static final int MAX_QUEEN_SIZE_10000 = 10000;
    //核心线程数
    private static final int CPUCores = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPUCores * 10;
    // 最大线程数
    private int maxThreadCount = 40;

    @Bean("orderPools")
    public ExecutorService orderPools() {
        int threadCount = CORE_POOL_SIZE;
        if (CPUCores > 10) {
            threadCount = maxThreadCount;
        }

        ThreadPoolExecutor orderExecutorService = new ThreadPoolExecutor(threadCount,   // 核心线程数
                threadCount * 2,                                                        // 最大线程数
                0L,                                                                     // 空闲线程存活时间
                TimeUnit.SECONDS,                                                       // 时间单位
                new LinkedBlockingQueue<>(MAX_QUEEN_SIZE_10000),                        // 任务队列
                Executors.defaultThreadFactory(),                                       // 线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy()                               // 拒绝策略
        );
        return EXECUTOR_SERVICE_LOADING_CACHE.computeIfAbsent("orderPools", k -> orderExecutorService);
    }
}
